package com.lzc.service.impl;

import cn.hutool.core.io.FileUtil;
import com.lzc.mapper.ImgLibraryMapper;
import com.lzc.pojo.dto.ImgLibraryDto;
import com.lzc.pojo.entity.ImgLibrary;
import com.lzc.pojo.vo.Result;
import com.lzc.service.FileUpLoadService;
import com.lzc.util.ThreadLocalUtil;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.buf.ByteBufferUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class FileUpLoadServiceImpl implements FileUpLoadService {

    // 头像
    @Value("${file.headImgParentPath}")
    private  String headImgParentPath;

    // 素材库图片
    @Value("${file.imgRealPath}")
    private  String imgRealPath;

    // 获取头像路径
    @Value("${api.headImgLoadUrl}")
    private  String headImgLoadUrl;

    // 获取素材库图片路径
    @Value("${api.imgLibraryUrl}")
    private  String imgLibraryUrl;

    @Value("${file.articleDiskPathPrefix}")
    private String articleDiskPathPrefix;

    @Autowired
    private ImgLibraryMapper imgLibraryMapper;

    /**
     * 浏览器上传文件到服务器
     * @param file 文件信息
     * @return
     */
    @Override
    public Result upLoadHeadImg(MultipartFile file){

        try {
            if (file == null || file.isEmpty()){
                return Result.FILE("上传失败 ! ! ");
            }
            String fileName = saveFileToDisk(file, headImgParentPath);

            return Result.OK(headImgLoadUrl + fileName);

        } catch (Exception e) {

            e.printStackTrace();

            return Result.FILE("上传失败 ! ! ");
        }
    }

    /**
     * 浏览器获取图片
     * @param imgName 图片名
     * @param response 响应体
     */
    @Override
    public void loadHeadImg(String imgName, HttpServletResponse response) {

        // 获取输出流
        try(ServletOutputStream outputStream = response.getOutputStream()) {

            // 设置响应格式
            response.setContentType("image/jpeg");

            FileUtils.copyFile(new File(headImgParentPath + imgName), outputStream);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 浏览器上传图片到素材库
     * @param files 图片
     * @return
     */
    @Override
    public Result upLoadImg(MultipartFile[] files) {
        if (files == null || files.length == 0){
            return Result.FILE("图片上传失败！请重试!");
        }

        List<Long> fileList = new ArrayList<>();
        for (MultipartFile file : files) {
            try {

                if (file == null || file.isEmpty()){
                    return Result.FILE("图片上传失败！请重试!");
                }

                // 保存到磁盘
                String fileName = saveFileToDisk(file, imgRealPath);

                // 保存到数据库
                ImgLibrary imgLibrary = new ImgLibrary();
                imgLibrary.setSrc(imgLibraryUrl + fileName);
                imgLibrary.setUid(ThreadLocalUtil.getUid());
                imgLibrary.setState((byte) 1);
                imgLibraryMapper.insert(imgLibrary);

                fileList.add(imgLibrary.getId());

            }catch (Exception e) {

                e.printStackTrace();

                return Result.FILE("上传失败 ! ! ");
            }
        }
        return Result.OK(fileList);
    }

    /**
     * 查看素材库的图片
     */
    @Override
    public void loadImg(String imgName, HttpServletResponse response) {
        // 获取输出流
        try(ServletOutputStream outputStream = response.getOutputStream()) {

            // 设置响应格式
            response.setContentType("image/jpeg");

            FileUtils.copyFile(new File(imgRealPath + imgName), outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看文章
     * @param response 返回值
     */
    @Override
    public void loadArticle(HttpServletRequest request, HttpServletResponse response) {
        String uri = request.getRequestURI();
        String path = uri.split("article/")[1];

        // 获取输出流
        try(ServletOutputStream outputStream = response.getOutputStream()) {

            // 设置响应格式
            if (path.contains(".html")){
                response.setContentType("text/html;charset=utf-8");
            }

            FileUtils.copyFile(new File(articleDiskPathPrefix + path), outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存到磁盘
     * @param file 文件
     * @param path 磁盘路径
     * @return 文件名
     */
    private String saveFileToDisk(MultipartFile file, String path){
        // 获取输入流
        try(InputStream inputStream = file.getInputStream()) {
            // 获取文件名
            String filename = file.getOriginalFilename();
            // 修改文件名
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
            String name = LocalDateTime.now().format(pattern) + filename;

            // 存入文件
            //TODO 后续可扩展为上传到文件服务器
            String endPath = path + name;

            FileUtils.copyInputStreamToFile(inputStream , new File(endPath));

            return name;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }


}
